<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入查询关键词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDepartments">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments"
              highlight-current-row
              v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="sn" label="部门编号" sortable></el-table-column>
      <el-table-column prop="name" label="部门名称" sortable></el-table-column>
      <el-table-column prop="dirPath" label="部门层级" sortable></el-table-column>
      <el-table-column prop="state" label="状态" :formatter="formatState" sortable>
        <template scope="scope">
          <span v-if="scope.row.state === 1" style="color: #11b95c">启用</span>
          <span v-else-if="scope.row.state === 0" style="color: rgba(185,17,17,0.92)">禁用</span>
          <span v-else style="color: #18bfda">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" sortable></el-table-column>
      <el-table-column prop="parent.name" label="上级部门" sortable></el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--分页器-->
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
      <el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="departmentForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="departmentForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="departmentForm.manager" value-key="id" clearable placeholder="请选择">
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <!-- 向下拉会显示名字和手机 -->
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="departmentForm.parent"
                       :options="deptTree"
                       :props="{
                         checkStrictly:true,
                         label:'name',
                         value:'id'
                       }"
                       clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="departmentFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import {
  getDepartmentListPage,
  removeDepartment,
  batchRemoveDepartment,
  addOrEditDepartment,
  getEmployeeList, getDepartmentTree
} from '@/api/api';

export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      // 下拉框的部门
      departments: [],
      // 下拉框的经理
      employees: [],
      // 级联部门树
      deptTree: [],
      total: 0,
      title: '',
      page: 1,
      pageSize: 8,
      listLoading: false,
      sels: [],//列表选中列

      departmentFormVisible: false,//编辑界面是否显示
      departmentLoading: false,
      //  编辑、修改界面的数据的规则
      //  需要用prop绑定
      departmentFormRules: {
        sn: [{required: true, message: '请输入编号', trigger: 'blur'}],
        name: [{required: true, message: '请输入部门名称', trigger: 'blur'}],
        state: [{required: true, message: '请选择状态', trigger: 'blur'}],
      },
      // 编辑、修改界面的数据
      departmentForm: {
        id: null,
        sn: '',
        name: '',
        state: 0,
        manager: null,
        parent: null
      },

    }
  },
  methods: {
    //状态显示转换
    formatState(row) {
      return row.state === 1 ? '启用' : row.state === 0 ? '禁用' : '未知';
    },
    // 切换页面
    handleCurrentChange(val) {
      this.page = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      let para = {
        currentPage: this.page,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      console.log("页码信息", para);
      this.listLoading = true;
      getDepartmentListPage(para).then((res) => {
        console.log("部门信息：", res);
        this.total = res.total;
        // console.log(this.total)
        this.departments = res.rows;
        this.listLoading = false;

        // 查询完了回第一页
        // 防止出现在第二页查找，但是符合要求的数据不够显示到第二页，会导致无数据
        this.page = 1;
      });
    },
    // 获取二级部门树
    getDepartmentTree() {
      getDepartmentTree().then((result) => {
        console.log("二级部门树：", result)
        this.deptTree = result
      })
    },
    //获取部门经理列表
    getEmployees() {
      getEmployeeList().then((res) => {
        console.log("部门经理：", res);
        this.employees = res;
      });
    },
    //删除
    handleDel(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        removeDepartment(row.id).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.page = 1;
          this.getDepartments();
        });
      }).catch(() => {
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = '编辑部门';
      this.departmentFormVisible = true;
      // 整理数据回显到编辑页面
      this.departmentForm = Object.assign({}, row);
      // 死数据展示
      // this.departmentForm.parent = [2, 5];  显示的就是2号部门/5号部门

      let dirPath = this.departmentForm.dirPath;
      // 拿出后端传来的这个部门dirPath的值
      if (dirPath) {
        // console.log("dirPath", dirPath) // 数据是：/2/5/11
        // 通过斜杠来用split分割放到数组里面
        let splitArray = dirPath.split("/");
        // console.log("splitArray",splitArray)   //  ['', '2', '5', '11']
        // 需要取出来放到数组里，再赋值给 this.departmentForm.parent
        let parentDir = [];
        // 因为第一个是空的，最后一个是本部门，所以取中间的参数
        for (let i = 1; i < splitArray.length - 1; i++) {
          // 需要把字符型转换为int型
          parentDir.push(parseInt(splitArray[i]));  // [2,5]
        }
        // console.log("parentDir",parentDir)
        // 赋值给parent，可以进行数据的回显了
        this.departmentForm.parent = parentDir;
      }
      this.getDepartmentTree()
    },
    //显示新增界面
    handleAdd() {
      this.title = '新增部门';
      this.departmentFormVisible = true;
      // 置空数据，因为是新增
      this.departmentForm = {
        id: null,
        sn: '',
        name: '',
        state: 0,
        manager: null,
        parent: null
      };
      this.getDepartmentTree()
    },
    // 操作部门，增加或编辑
    departmentSubmit() {
      console.log("提交的数据", this.title);
      // 首先校验数据
      this.$refs.departmentForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.departmentLoading = true;
            let para = Object.assign({}, this.departmentForm);
            console.log("提交的数据", para);
            // 如果manager为空,即部门经理为空
            if (!para.manager) {
              para.manager = {"id": null};
            }
            // 判断parent是否为空 不空就返回一个id给后端存值
            let parent = para.parent;
            if (parent) {
              let parentId = parent[parent.length - 1];
              para.parent = {"id": parentId}
            }

            addOrEditDepartment(para).then((res) => {
              this.departmentLoading = false;
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['departmentForm'].resetFields();
              this.departmentFormVisible = false;
              this.getDepartments();
            });
          });
        }
      });
    },
    selsChange(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove() {
      let ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        console.log("删除参数", ids);
        batchRemoveDepartment(ids).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartments();
        });
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getDepartments();
    this.getEmployees();
  }
}

</script>

<style scoped>

</style>
